<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_chatgpt/model')->方法名();
*/
namespace jy_chatgpt;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	//发起http请求
	public function request($rurl,$post=null,$isres=false){
		$basic=$this->plugin_setting('basic');
		if(!$basic['apikey']){
			if($isres){
				$res['choices'][0]['text']='chatGPT暂时无法使用，请联系管理员，设置好基本参数API Key';
				return $res;
			}else{
				exi('chatGPT暂时无法使用，请联系管理员，设置好基本参数API Key','error');
			}
		}
		$extra=array(
				'Content-Type' => 'application/json',
				'Authorization'=> 'Bearer '.$basic['apikey']
		);
		$post=ijson_encode($post);
		$result=cfc('http')->ihttp_request($rurl,$post,$extra);
		if(is_error($result)){			
			$message="访问失败, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$data=@json_decode($data,true);
		if($data['errcode']){
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
			$message='访问接口错误，以下为原始数据：'.$result['content'];
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		return $data;
	}
	public function requestchatapi($rurl,$post=null,$isres=false){
		$basic=$this->plugin_setting('basic');
		if(!$basic['apikey']){
			if($isres){
				$res['choices'][0]['text']='chatGPT暂时无法使用，请联系管理员，设置好基本参数API Key';
				return $res;
			}else{
				exi('chatGPT暂时无法使用，请联系管理员，设置好基本参数API Key','error');
			}
		}
		$post['apikey']=$basic['apikey'];
		$apipost=array(
			'do'=>'get',
			'data'=>$post,
			'timestamp'=>TIMESTAMP,
		);
		$key_str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
		$post=cfc('tools')->base64_encode(json_encode($apipost),$key_str);
		$sign=md5($post.'Y2hhdC5qaW55dW53ZWIuY29t');
		$post=$sign.$post;
		$params=array(
			'data'=>$post,
		);
		$post_url='http://chatapi.jinyunweb.com/api.php';
		$res=cfc('http')->ihttp_request($post_url,$params);
		if(!$res['content']){
			exi('访问接口站失败！没有收到数据：'.$res['code'],'error');
		}
		$res=$res['content'];
		$res=@unserialize(base64_decode($res));
		//print_r($res['message']);exit;
		if($res['type']=='success'){
			return $res['message'];
		}else{
			exi('访问接口站失败！错误详情：'.$res['message'],'error');
		}
	}
	//获取聊天文本
	public function getmsg($content,$isexi=false) {
		$basic=$this->plugin_setting('basic');
		if($basic['isku']){
			$msg=$this->getwenda($content);
			if($msg){
				return $msg;
			}
		}
		if(strpos($basic['apis'],'0') !== false){
			
		}else{
			if(strpos($basic['apis'],'1') !== false){
				return $this->model('tuling')->getmsg($content,$isexi);
			}
			return '';
		}
		//return '这里是测试数据！这里是测试数据！这里是测试数据！这里是测试数据！这里是测试数据！这里是测试数据！';
		//text-davinci-003 gpt-3.5-turbo
		$url = $basic['apiurl']?:"https://api.openai.com/v1/chat/completions";
		/*$post=array(
			'model'=>'text-davinci-003',
			'prompt'=>$content,
			'max_tokens'=>2048,
		);*/
		$messages[]=array('role'=>'user','content'=>$content);
		$post=array(
			'model'=>'gpt-3.5-turbo',
			'messages'=>$messages,
			'temperature'=>0.7,
		);
		$res=$this->request($url,$post,true);
		if($res['error']){
			if(strpos($basic['apis'],'1') !== false){
				return $this->model('tuling')->getmsg($content,$isexi);
			}
			$res['message']=$res['message']?:$res['error']['message'];
			if($isexi){
				exi('获取失败：'.$res['type'].','.$res['message'],'error');
			}else{
				return $basic['nomsg']?:'chatGPT暂时无法回答您的问题！请联系管理员！';
			}
		}
		//$msg=$res['choices'][0]['text'];
		$msg=$res['choices'][0]['message']['content'];
		if($msg){
			$this->upwenda($content,$msg);
		}
		return $msg;
	}
	public function yufee() {
		$basic=$this->plugin_setting('basic');
		if(!$basic['apikey']){
			return false;
		}
		$url = "https://api.openai.com/v1/chat/completions";
		$messages[]=array('role'=>'user','content'=>$content);
		$post=array(
			'model'=>'gpt-3.5-turbo',
			'messages'=>$messages,
			'temperature'=>0.7,
		);
		$res=$this->request($url,$post,true);
		if($res['error']){
			$res['message']=$res['message']?:$res['error']['message'];
			if($isexi){
				exi('获取失败：'.$res['type'].','.$res['message'],'error');
			}else{
				return '获取余额失败：'.$res['message'];
			}
		}
		$msg=$res['choices'][0]['message']['content'];
		return $msg;
	}
	public function getwenda($msg=''){
		$wenda=pdo_get('jy_chatgpt_wenda',array('title like'=>'%'.trim($msg).'%','status'=>1,'uniacid'=>$_SESSION['uniacid']),'','paixu desc,id desc');
		return $wenda['msg'];
	}
	//机器人入库
	public function upwenda($title='',$msg=''){
		$wenda=pdo_get('jy_chatgpt_wenda',array('title'=>trim($title),'uniacid'=>$_SESSION['uniacid']));
		if($wenda['id'] || !$title || !$msg){
			return false;
		}
		$data=array(
			'uniacid'=>$_SESSION['uniacid'],
			'title'=>$title,
			'msg'=>$msg,
			'status'=>1,
			'createtime'=>TIMESTAMP
		);
		pdo_insert('jy_chatgpt_wenda',$data);
		return true;
	}
}
?>